package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("setmeal")
public class SetMealController {

    @DubboReference
    private SetMealService setMealService;

    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean){
        /*
        * @Date: 10:44 上午 2021/1/6
        * @param: [queryPageBean]
        * @return: com.itheima.health.entity.Result
        * @Description: 查询所有信息并分页返回
        */
        log.info("[预约-套餐-findPage-前端传入数据] - queryPageBean - {}",queryPageBean);
        PageResult pageResult = setMealService.findPage(queryPageBean);
        log.info("[预约-套餐-findPage-后端返回数据] - pageResult - {}",pageResult);

        if (pageResult==null){
            return new Result(false, MessageConst.QUERY_SETMEAL_FAIL);
        }
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,pageResult);
    }

    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    @PostMapping("upload")
    public Result imageUpload(@RequestParam("imgFile")MultipartFile multipartFile){
        /*
        * @Date: 12:27 下午 2021/1/6
        * @param: [multipartFile]
        * @return: com.itheima.health.entity.Result
        * @Description: 使用MultipartFile进行上传文件
        */
        //封装上传时图片的名字
        String name = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = System.currentTimeMillis()+"_"+uuid+"_"+name;
        try {
            InputStream is = multipartFile.getInputStream();
            //调用文件上传方法
            qiniuUtils.upload2Qiniu(is,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("[预约-套餐-upload-图片上传失败] - e: {} ",e.getMessage());
            return new Result(false,MessageConst.PIC_UPLOAD_FAIL);
        }
        //把图片的名字存入redis中，用于定时清理
        redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).add(fileName);

        /**
         * qiniuUtils.getUrlPrefix()：返回域名
         * qiniuUtils.getUrlPrefix()+fileName：拼接上传时图片名称并返回完成url
         * urlPrefix：拼接后的url，进行前端展示预览
         */
        String urlPrefix = qiniuUtils.getUrlPrefix()+fileName;
        log.info("[预约-套餐-upload-后端返回数据] - urlPrefix - {}",urlPrefix);
        return new Result(true,MessageConst.PIC_UPLOAD_SUCCESS,urlPrefix);
    }


    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    @PostMapping("add")
    public Result add(@RequestBody Setmeal setmeal,@RequestParam("checkgroupIds") Integer[] checkGroupIds){
        /*
        * @Date: 3:24 下午 2021/1/6
        * @param: [setmeal, ids]
        * @return: com.itheima.health.entity.Result
        * @Description: 上传套餐信息和检查组信息
        */
        //判断图片不等于空进行切割取出fileName再进行存入
        if (!StringUtils.isEmpty(setmeal.getImg())){
            String img = setmeal.getImg().replace(qiniuUtils.getUrlPrefix(), "");
            setmeal.setImg(img);
        }
        log.info("[预约-套餐-add-前端传入数据] - setmeal: {} - checkGroupIds: {}",setmeal,checkGroupIds);
        boolean flag = setMealService.add(setmeal,checkGroupIds);
        if (!flag){
            return new Result(false,MessageConst.ADD_SETMEAL_FAIL);
        }
        //添加成功之后把图片名字从redis中删除
        redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(setmeal.getImg());

        //查询剩余垃圾图片
        Set members = redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        log.info("[预约-套餐-add-redis中剩余垃圾图片] - set: {}",members);

        return new Result(true,MessageConst.ADD_SETMEAL_SUCCESS);
    }






}
